import React, { createContext, useContext, useState, ReactNode } from 'react';
import { message } from 'antd';

interface LlmSettings {
  provider: string;
  endpoint: string;
  apiKey: string;
  model: string;
}

interface EmbeddingSettings {
  provider: string;
  endpoint: string;
  apiKey: string;
  model: string;
  dimensions: number;
  normalize: boolean;
  batchSize: number;
  showAdvanced: boolean;
}

interface RetrievalSettings {
  type: string;
  endpoint: string;
  apiKey: string;
  indexName: string;
  namespace: string;
  dimensions: number;
}

interface ApiSettings {
  llm: LlmSettings;
  embedding: EmbeddingSettings;
  retrieval: RetrievalSettings;
  baseUrl: string;
  apiKey: string | null;
  version: string;
  timeout: number;
}

interface ApiSettingsContextType {
  settings: ApiSettings;
  apiSettings: ApiSettings; // Alias for backwards compatibility
  updateSettings: (newSettings: Partial<ApiSettings>) => void;
  resetSettings: () => void;
}

const defaultSettings: ApiSettings = {
  llm: {
    provider: 'openai',
    endpoint: 'https://api.openai.com/v1/chat/completions',
    apiKey: '',
    model: 'gpt-4',
  },
  embedding: {
    provider: 'openai',
    endpoint: 'https://api.openai.com/v1/embeddings',
    apiKey: '',
    model: 'text-embedding-ada-002',
    dimensions: 1536,
    normalize: true,
    batchSize: 20,
    showAdvanced: false,
  },
  retrieval: {
    type: 'pinecone',
    endpoint: '',
    apiKey: '',
    indexName: 'default',
    namespace: '',
    dimensions: 1536,
  },
  baseUrl: 'https://api.example.com',
  apiKey: null,
  version: 'v1',
  timeout: 30000, // 30秒
};

const ApiSettingsContext = createContext<ApiSettingsContextType>({
  settings: defaultSettings,
  apiSettings: defaultSettings, // Alias for backwards compatibility
  updateSettings: () => {},
  resetSettings: () => {},
});

export const useApiSettings = () => useContext(ApiSettingsContext);

interface ApiSettingsProviderProps {
  children: ReactNode;
}

export const ApiSettingsProvider: React.FC<ApiSettingsProviderProps> = ({ children }) => {
  const [settings, setSettings] = useState<ApiSettings>(() => {
    // 从本地存储加载设置
    const savedSettings = localStorage.getItem('api-settings');
    return savedSettings ? JSON.parse(savedSettings) : defaultSettings;
  });
  
  const updateSettings = (newSettings: Partial<ApiSettings>) => {
    const updatedSettings = { ...settings, ...newSettings };
    setSettings(updatedSettings);
    // 保存到本地存储
    localStorage.setItem('api-settings', JSON.stringify(updatedSettings));
  };
  
  const resetSettings = () => {
    setSettings(defaultSettings);
    localStorage.removeItem('api-settings');
    message.success('已重置所有服务设置');
  };
  
  return (
    <ApiSettingsContext.Provider value={{ settings, apiSettings: settings, updateSettings, resetSettings }}>
      {children}
    </ApiSettingsContext.Provider>
  );
}; 